package com.hnd.springframework.beans.factory.support.InstantiationStrategyImpl;

import com.hnd.springframework.beans.BeansException;
import com.hnd.springframework.beans.factory.config.BeanDefinition;
import com.hnd.springframework.beans.factory.support.InstantiationStrategy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition, Constructor ctor, String beanName, Object... args) {
        Class beanClass = beanDefinition.getBeanClass();
        try {
            if (ctor == null) {
                return beanClass.newInstance();
            }
            return beanClass.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);

        } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
            throw new BeansException("bean 实例化失败", e);
        }

    }
}
